#!/usr/bin/env bash
set -e

OWNER="microsoft"
REPO="edit"
INSTALL_PATH="$HOME/.local/bin/edit"

mkdir -p "$(dirname "$INSTALL_PATH")"

# 检测架构
ARCH=$(uname -m)
case "$ARCH" in
    x86_64) ARCH_TAG="x86_64-linux-gnu" ;;
    aarch64) ARCH_TAG="aarch64-linux-gnu" ;;
    *) echo "❌ 不支持的架构: $ARCH"; exit 1 ;;
esac
echo "🔍 检测到架构: $ARCH -> $ARCH_TAG"

# 检查本地版本
if [ -x "$INSTALL_PATH" ]; then
    LOCAL_VERSION=$($INSTALL_PATH --version 2>/dev/null | grep -oE "[0-9]+\.[0-9]+\.[0-9]+")
    echo "📦 本地版本: ${LOCAL_VERSION:-未检测到}"
else
    LOCAL_VERSION=""
    echo "📦 本地未安装 edit"
fi

# 获取最新 release 信息
API_URL="https://api.github.com/repos/${OWNER}/${REPO}/releases/latest"
RELEASE_JSON=$(curl -sL "$API_URL")
LATEST_VERSION=$(echo "$RELEASE_JSON" | grep '"tag_name":' | cut -d '"' -f 4 | sed 's/^v//')
echo "🌐 线上最新版本: $LATEST_VERSION"

# 版本比较
if [ "$LOCAL_VERSION" = "$LATEST_VERSION" ]; then
    echo "✅ 已是最新版本，无需更新"
    exit 0
fi
echo "⬆️ 检测到新版本，准备更新..."

# 获取下载链接
ASSET_URL=$(echo "$RELEASE_JSON" | grep "browser_download_url" | grep "$ARCH_TAG" | cut -d '"' -f 4)
if [ -z "$ASSET_URL" ]; then
    echo "❌ 未找到匹配的下载链接"
    exit 1
fi

ASSET_FILE=$(basename "$ASSET_URL")
TMP_DIR=$(mktemp -d)
cd "$TMP_DIR"

echo "📦 正在下载 $ASSET_FILE..."
curl -L -o "$ASSET_FILE" "$ASSET_URL"

# SHA256 信息
echo "🔍 文件 sha256: $(sha256sum "$ASSET_FILE" | awk '{print $1}')"

# 解压
echo "📂 正在解压 $ASSET_FILE..."
if [[ "$ASSET_FILE" == *.tar.zst ]]; then
    if command -v tar >/dev/null && tar --help 2>&1 | grep -q zstd; then
        tar --zstd -xf "$ASSET_FILE"
    else
        if ! command -v unzstd >/dev/null; then
            echo "❌ 未安装 zstd，请安装: sudo apt install zstd"
            exit 1
        fi
        TMP_TAR="${ASSET_FILE%.zst}"
        unzstd -f "$ASSET_FILE" -o "$TMP_TAR"
        tar -xf "$TMP_TAR"
        rm -f "$TMP_TAR"
    fi
else
    tar -xf "$ASSET_FILE"
fi

# 安装可执行文件
if [ -f "edit" ]; then
    mv edit "$INSTALL_PATH"
    chmod +x "$INSTALL_PATH"
    echo "✅ 安装完成，新版本: $LATEST_VERSION"
else
    echo "❌ 未找到 edit 可执行文件"
    exit 1
fi

# 清理临时文件
cd ~
rm -rf "$TMP_DIR"
